/*************************************
 * Created by WebStorm
 * Author : 菲尔敦
 * QQ邮箱：2891044172@qq.com  手机号：15981761402
 * Created Time :2024/2/5 18:23
 Desc :
 **************************************/
import {defineStore} from 'pinia';
import type {RouteRecordRaw} from 'vue-router';
import {setLocalStorage, getLocalStorage, generateRoutesByServer, generatorMenu} from '@/util'
import routers from '@/router/routers';
import {store} from '@/stores';
import {toRaw} from 'vue';
import type {MenuOption} from 'naive-ui'
import {Config, Copyright} from '@/config'

import {getRequest} from "@/api/data.ts";


interface AppsState {
    title: string | any,//系统标题(名称)
    logo?: string | number | null | any | bigint,//logo
    copyright: string,
    icp: string,
    icp_url: string,
    theme: String | Boolean;//主题 深色、浅色
    LoadingLoginBtn: boolean;//登录按钮加载
    tabsList: any[];//主体上的tabs
    tabsStyle: string; //tabs 样式
    menus: RouteRecordRaw[]; //菜单
    routers: any[]; //路由
    addRouters: any[];//动态路由
    keepAliveComponents: string[];
    isDynamicAddedRoute: boolean;
    permissionDisabled: boolean, //是否所有没有权限的按钮变成disabled  是:true  否:false
    paddingTeacher: number,//待处理教师数量
    paddingOrder: number,//待处理订单数量
    paddingWOrder: number,//待处理提现申请数量
    paddingFeedback: number,//待处理的反馈意见

}

export const UseAppStore = defineStore({
    id: "app",
    state: (): AppsState => ({
        title: getLocalStorage("title") || Config.Title,
        logo: '',
        copyright: '' || Copyright.copyright,
        icp: '' || Copyright.icp,
        icp_url: '',
        theme: getLocalStorage("theme") || "light",
        LoadingLoginBtn: false,
        tabsList: getLocalStorage("tabs_list") || [],
        tabsStyle: "is_background",
        menus: [],
        routers: routers,
        addRouters: [],
        keepAliveComponents: [],
        isDynamicAddedRoute: false,
        permissionDisabled: false,
        paddingTeacher: 0,//待处理教师数量
        paddingOrder: 0,//待处理订单数量
        paddingWOrder: 0,//待处理提现申请数量
        paddingFeedback:0,//待处理的反馈意见
    }),
    getters: {
        getMenus(state): MenuOption[] {
            return generatorMenu(state.routers)
        }
    },
    actions: {
        //设置暗黑主题
        setTheme(theme: string | boolean) {
            setLocalStorage("theme", theme);
            this.theme = theme;
        },
        //添加tabs
        addTabs(route: any) {
            const isExists = this.tabsList.some((item) => item.path === route.path);
            if (isExists && route.name !== "notFound" && route.name !== "login") {
                const index = this.tabsList.findIndex(
                    (item) => item.path === route.path
                );
                this.tabsList[index] = route;
            } else if (
                !isExists &&
                route.name !== "notFound" &&
                route.name !== "login"
            ) {
                this.tabsList.push(route);
            }
            this.updateTabs(this.tabsList)
            return true;
        },
        // 关闭当前页
        CloseCurrentTabs(route: any) {
            const index = this.tabsList.findIndex(
                (item) => item.fullPath === route.fullPath
            );
            this.tabsList.splice(index, 1);
            this.updateTabs(this.tabsList)
        },
        //关闭其他标签页
        CloseOtherTabs(route: any) {
            const Others = this.tabsList.filter(
                (item) => item.fullPath === route.fullPath || item.name === "home"
            );
            this.tabsList = Others;
            this.updateTabs(Others)
        },
        //关闭其他标签页
        CloseAllTabs() {
            const home = this.tabsList.filter((item) => item.name === "home");
            this.tabsList = home;
            this.updateTabs(home)
        },
        //更新tabs
        updateTabs(tabs: any) {
            setLocalStorage("tabs_list", tabs);
        },
        //是否动态添加
        setDynamicAddedRoute(added: boolean) {
            this.isDynamicAddedRoute = added;
        },
        setKeepAliveComponents(compNames: string[]) {
            // 设置需要缓存的组件
            this.keepAliveComponents = compNames;
        },
        // 设置动态路由
        setRouters(router: any[]) {
            this.addRouters = router;
            this.routers = routers.concat(router);
        },
        //token失效跳出登录页面是
        async tokenFailure() {
            this.addRouters = [];
            this.isDynamicAddedRoute = false;
        },
        async generateRoutes() {
            const routers = getLocalStorage("menu_routers")
            const asyncRoutes: any[] = generateRoutesByServer(routers);
            this.setRouters(asyncRoutes);
            this.setDynamicAddedRoute(true)
            return toRaw(asyncRoutes);
        },
        //更新标题
        setTitle(title: string | null) {
            const window_title = document.title;
            let new_title: any;
            if (window_title.includes("-")) {
                const parts = window_title.split("-");
                new_title = parts[1];
            }
            this.title = title;
            setLocalStorage('title', title);
            document.title = title ? title + '-' + new_title : new_title;
        },
        //更新logo
        setLogo(logo: string | null) {
            this.logo = logo ? '/api/admin/file/' + logo : '';
        },
        //icp
        setICP(icp: string | any, icp_url: string | any) {
            this.icp = icp;
            this.icp_url = icp_url;
        },
        //copyright
        setCopyright(copyright: string | any) {
            this.copyright = copyright;
        },
        //获取系统配置
        async getConfig() {
            await getRequest('get_config').then((result: ResponseResult) => {
                const {data} = result;
                this.setTitle(data.title !== undefined ? data.title : '');
                this.setLogo(data.logo !== undefined ? data.logo : '');
                this.setICP(data.icp !== undefined ? data.icp : '', data.icp_url !== undefined ? data.icp_url : '');
                this.setCopyright(data.copyright !== undefined ? data.copyright : '');
            })
        },
        //待处理教师数量
        setPaddingTeacher(value: number, increase: boolean = false) {
            if (increase) {
                this.paddingTeacher += value;
            } else {
                this.paddingTeacher = value;
            }

        },
        //待处理订单数量
        setPaddingOrder(value: number, increase: boolean = false) {
            if (increase) {
                this.paddingOrder += value;
            } else {
                this.paddingOrder = value;
            }
        },
        //待处理提现申请数量
        setPaddingWOrder(value: number, increase: boolean = false) {
            if (increase) {
                this.paddingWOrder += value;
            } else {
                this.paddingWOrder = value;
            }
        },
        //反馈意见
        setPaddingFeedback(value: number, increase: boolean = false){
            if (increase) {
                this.paddingFeedback += value;
            } else {
                this.paddingFeedback = value;
            }
        }
    },
});

export function useAsyncRouteStoreWidthOut() {
    return UseAppStore(store);
}